<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级项目业绩管理系统</title>
    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f6fa;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .input-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }

        .input-group {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }

        input, select, button {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        button {
            background-color: var(--secondary-color);
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #2980b9;
        }

        .data-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .data-box {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: var(--primary-color);
            color: white;
        }

        .highlight {
            color: #27ae60;
            font-weight: bold;
        }

        @media (max-width: 768px) {
            .input-group {
                grid-template-columns: 1fr;
            }
        }
        .project-highlight {
            background-color: #f8f9fa;
            font-weight: 500;
        }
        .alert {
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            display: none;
        }
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
        }

        /* 新增编辑相关样式 */
        .edit-mode { background-color: #fff3cd; }
        .action-buttons { display: flex; gap: 5px; }
        .btn-edit { background-color: #ffc107; }
        .btn-delete { background-color: #dc3545; }
        /* 新增筛选相关样式 */    
        .filter-section {
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .filter-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="alert alert-error" id="errorAlert"></div>

        <div class="input-section">
            <h2>项目登记/编辑</h2>
            <div class="input-group">
                <input type="text" id="project" placeholder="项目名称*" required>
                <input type="number" id="projectSales" placeholder="总销售额（万）*" step="0.1" required>
                <input type="number" id="refund" placeholder="返款金额（万）" step="0.1">
                <input type="text" id="name" placeholder="成员姓名*" required>
                <input type="date" id="date" required>
                <input type="number" id="personalSales" placeholder="个人业绩（万）*" step="0.1" required>
                <input type="text" id="remark" placeholder="备注">
                <button onclick="saveRecord()" id="saveBtn">保存记录</button>
                <button onclick="cancelEdit()" id="cancelBtn" style="display:none">取消编辑</button>
            </div>
        </div>

        <!-- 在container内添加筛选模块 -->
        <div class="filter-section">
            <h3>数据筛选</h3>
            <div class="filter-group">
                <input type="date" id="startDate">
                <input type="date" id="endDate">
                <button onclick="applyFilter()">应用筛选</button>
                <button onclick="clearFilter()">清除筛选</button>
            </div>
        </div>

        <div class="data-section">
            <div class="data-box">
                <h3>项目总览</h3>
                <table id="projectSummary">
                    <thead>
                        <tr>
                            <th>项目名称</th>
                            <th>总销售额</th>
                            <th>返款</th>
                            <th>净收入</th>
                            <th>参与人数</th>
                            <th>完成度</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
            <div class="data-box">
                <h3>个人排名</h3>
                <table id="personalRanking"></table>
            </div>
        </div>

        <div class="data-box" style="margin-top:20px">
            <h3>详细记录 <button onclick="exportData()" style="float:right">导出数据</button></h3>
            <table id="allRecords">
                <thead>
                    <tr>
                        <th>操作</th>
                        <th>项目名称</th>
                        <th>总销售额</th>
                        <th>返款</th>
                        <th>净收入</th>
                        <th>成员</th>
                        <th>个人业绩</th>
                        <th>贡献率</th>
                        <th>日期</th>
                        <th>备注</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
    </div>

<script>
let records = JSON.parse(localStorage.getItem('projectRecordsV3')) || [];
let editId = null;
let projects = {};

// 初始化项目缓存
function initProjects() {
    projects = {};
    records.forEach(record => {
        projects[record.project] = {
            sales: record.projectSales,
            refund: record.refund || 0
        };
    });
}

// 在JavaScript部分添加以下代码
let dateFilter = {
    start: null,
    end: null
};

function applyFilter() {
    const start = document.getElementById('startDate').value;
    const end = document.getElementById('endDate').value;
    
    // 日期有效性验证
    if (start && end && start > end) {
        showError("结束日期不能早于开始日期");
        return;
    }
    
    dateFilter.start = start || null;
    dateFilter.end = end || null;
    updateDisplay();
}

function clearFilter() {
    document.getElementById('startDate').value = '';
    document.getElementById('endDate').value = '';
    dateFilter = { start: null, end: null };
    updateDisplay();
}

// 修改后的数据获取方法
function getFilteredRecords() {
    return records.filter(record => {
        const recordDate = new Date(record.date);
        const start = dateFilter.start ? new Date(dateFilter.start) : null;
        const end = dateFilter.end ? new Date(dateFilter.end) : null;
        
        let valid = true;
        if (start) valid = valid && recordDate >= start;
        if (end) valid = valid && recordDate <= end;
        return valid;
    });
}

function showError(message) {
    const alert = document.getElementById('errorAlert');
    alert.textContent = message;
    alert.style.display = 'block';
    setTimeout(() => alert.style.display = 'none', 3000);
}

function saveRecord() {
    const record = {
        id: editId || Date.now(),
        project: document.getElementById('project').value.trim(),
        projectSales: parseFloat(document.getElementById('projectSales').value),
        refund: parseFloat(document.getElementById('refund').value) || 0,
        name: document.getElementById('name').value.trim(),
        date: document.getElementById('date').value,
        personalSales: parseFloat(document.getElementById('personalSales').value),
        remark: document.getElementById('remark').value.trim()
    };

    // 数据验证
    if (record.refund > record.projectSales) {
        showError("返款金额不能超过总销售额");
        return;
    }

    if (projects[record.project] && !editId) {
        if (projects[record.project].sales !== record.projectSales ||
            projects[record.project].refund !== record.refund) {
            showError("项目信息修改请通过编辑原有记录操作");
            return;
        }
    }

    // 更新或新增记录
    const index = records.findIndex(r => r.id === record.id);
    if (index > -1) {
        records[index] = record;
    } else {
        records.push(record);
    }
    
    // 更新项目缓存
    projects[record.project] = {
        sales: record.projectSales,
        refund: record.refund
    };
    
    localStorage.setItem('projectRecordsV3', JSON.stringify(records));
    updateDisplay();
    cancelEdit();
}

function editRecord(id) {
    const record = records.find(r => r.id === id);
    if (!record) return;

    // 填充表单
    document.getElementById('project').value = record.project;
    document.getElementById('projectSales').value = record.projectSales;
    document.getElementById('refund').value = record.refund;
    document.getElementById('name').value = record.name;
    document.getElementById('date').value = record.date;
    document.getElementById('personalSales').value = record.personalSales;
    document.getElementById('remark').value = record.remark;
    
    editId = id;
    document.getElementById('saveBtn').textContent = '更新记录';
    document.getElementById('cancelBtn').style.display = 'inline-block';
}

function deleteRecord(id) {
    if (!confirm('确定要删除这条记录吗？')) return;
    records = records.filter(r => r.id !== id);
    localStorage.setItem('projectRecordsV3', JSON.stringify(records));
    initProjects();
    updateDisplay();
}

function cancelEdit() {
    editId = null;
    document.getElementById('saveBtn').textContent = '保存记录';
    document.getElementById('cancelBtn').style.display = 'none';
    clearForm();
}

function clearForm() {
    document.getElementById('project').value = '';
    document.getElementById('projectSales').value = '';
    document.getElementById('refund').value = '';
    document.getElementById('name').value = '';
    document.getElementById('date').value = '';
    document.getElementById('personalSales').value = '';
    document.getElementById('remark').value = '';
}

function updateDisplay() {
    updateProjectSummary();
    updatePersonalRanking();
    updateAllRecords();
}

function updateProjectSummary() {
    const filteredRecords = getFilteredRecords();
    const projectData = {};
    
    filteredRecords.forEach(record => {
        if (!projectData[record.project]) {
            projectData[record.project] = {
                totalSales: record.projectSales,
                refund: record.refund,
                members: new Set(),
                personalTotal: 0
            };
        }
        projectData[record.project].members.add(record.name);
        projectData[record.project].personalTotal += record.personalSales;
    });

    const tbody = document.querySelector('#projectSummary tbody');
    tbody.innerHTML = Object.entries(projectData).map(([project, data]) => `
        <tr>
            <td class="project-highlight">${project}</td>
            <td>${data.totalSales.toFixed(1)}万</td>
            <td>${data.refund.toFixed(1)}万</td>
            <td>${(data.totalSales - data.refund).toFixed(1)}万</td>
            <td>${data.members.size}</td>
            <td>${((data.personalTotal / data.totalSales) * 100).toFixed(1)}%</td>
        </tr>
    `).join('');
}

function updatePersonalRanking() {
    const filteredRecords = getFilteredRecords();
    const memberData = {};

    filteredRecords.forEach(record => {
        if (!memberData[record.name]) {
            memberData[record.name] = {
                total: 0,
                projects: new Set(),
                totalRefund: 0
            };
        }
        memberData[record.name].total += record.personalSales;
        memberData[record.name].projects.add(record.project);
        memberData[record.name].totalRefund += record.refund;
    });

    const ranking = Object.entries(memberData)
        .sort((a, b) => b[1].total - a[1].total);

    const table = document.querySelector('#personalRanking');
    table.innerHTML = `
        <tr>
            <th>排名</th>
            <th>姓名</th>
            <th>总业绩</th>
            <th>净业绩</th>
            <th>参与项目</th>
        </tr>
        ${ranking.map(([name, data], index) => `
            <tr>
                <td>${index + 1}</td>
                <td>${name}</td>
                <td>${data.total.toFixed(1)}万</td>
                <td>${(data.total - data.totalRefund).toFixed(1)}万</td>
                <td>${data.projects.size}</td>
            </tr>
        `).join('')}
    `;
}

function updateAllRecords() {
    const filteredRecords = getFilteredRecords();
    const tbody = document.querySelector('#allRecords tbody');
    tbody.innerHTML = filteredRecords.map(record => {
        const netIncome = record.projectSales - record.refund;
        const contribution = (record.personalSales / record.projectSales * 100).toFixed(1);
        return `
            <tr>
                <td class="action-buttons">
                    <button class="btn-edit" onclick="editRecord(${record.id})">编辑</button>
                    <button class="btn-delete" onclick="deleteRecord(${record.id})">删除</button>
                </td>
                <td>${record.project}</td>
                <td>${record.projectSales.toFixed(1)}万</td>
                <td>${record.refund.toFixed(1)}万</td>
                <td>${netIncome.toFixed(1)}万</td>
                <td>${record.name}</td>
                <td>${record.personalSales.toFixed(1)}万</td>
                <td>${contribution}%</td>
                <td>${record.date}</td>
                <td>${record.remark || '-'}</td>
            </tr>
        `;
    }).join('');
}

function exportData() {
    const dataStr = JSON.stringify(records);
    const blob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `project_records_${new Date().toISOString().slice(0,10)}.json`;
    link.click();
}

// 初始化
initProjects();
updateDisplay();
</script>
</body>
</html>